package com.cold.legendary.bprocess.common.pool;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author cold
 * @since 2023/3/10
 */
public class ProcessThreadRunningPoolConfig {
    public static final int corePoolSize = 5;       		// 核心线程数（默认线程数）
    public static final int maxPoolSize = 100;			    // 最大线程数
    public static final int keepAliveTime = 30;			// 允许线程空闲时间（单位：默认为秒）
    public static final int queueCapacity = 10000;			// 缓冲队列数
    public static final String bProcessFinishPool = "bProcess-running-Pool-"; //

    private ThreadPoolTaskExecutor bprocessRunningExecutor = null;

    public static ThreadPoolTaskExecutor createExecutor(int corePoolSize, int maxPoolSize
            , int queueCapacity, String threadPrefix){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize == 0 ? ProcessThreadRunningPoolConfig.corePoolSize : corePoolSize);
        executor.setMaxPoolSize(maxPoolSize == 0 ? ProcessThreadRunningPoolConfig.maxPoolSize : maxPoolSize);
        executor.setQueueCapacity(queueCapacity == 0 ? ProcessThreadRunningPoolConfig.queueCapacity : queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadPrefix);
        executor.setWaitForTasksToCompleteOnShutdown(true);

        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }


    private ProcessThreadRunningPoolConfig() {

    }

    private static class ThreadPoolTaskConfigHoler {
        private static ProcessThreadRunningPoolConfig INSTANCE = new ProcessThreadRunningPoolConfig();
    }

    public static ProcessThreadRunningPoolConfig getInstance() {
        return ThreadPoolTaskConfigHoler.INSTANCE;
    }

    public synchronized ThreadPoolTaskExecutor getBProcessRunningPool(){
        if(bprocessRunningExecutor == null){
            bprocessRunningExecutor = createExecutor(corePoolSize, maxPoolSize, queueCapacity, bProcessFinishPool);
        }
        return bprocessRunningExecutor;
    }
}
